package com.bvbot.core.session;

import static com.bvbot.core.Logger.log;

import java.math.BigDecimal;

public class MarketResponse extends BvResponse {

	private static final BigDecimal BD_2 = new BigDecimal("2");

	public MarketResponse(String content) {
		super(content);
	}

	public BigDecimal getMarketPrice() throws BvSessionException {
		BigDecimal currentGoldPrice = null;
		try {
			BigDecimal highestBuyPrice = computeHighestBuyPrice();
			BigDecimal lowestSellPrice = computeLowestSellPrice();
			currentGoldPrice = highestBuyPrice.add(lowestSellPrice)
					.divide(BD_2);
		} catch (Exception e) {
			log("Error while computing current market price : "
					+ e.getMessage(), e);
		}
		return currentGoldPrice;
	}

	public BigDecimal computeLowestSellPrice() throws BvSessionException {
		BigDecimal result = null;
		int idxBuyPriceStartTag = getContent().indexOf("<sellPrices>");
		int idexBuyPriceEndTag = getContent().indexOf("</sellPrices>");
		String highBuyString = getContent().substring(idxBuyPriceStartTag,
				idexBuyPriceEndTag);
		String priceString = extractAttributValue("limit", highBuyString);
		result = new BigDecimal(priceString);
		return result;
	}

	public BigDecimal computeHighestBuyPrice() throws BvSessionException {
		BigDecimal result = null;
		int idxBuyPriceStartTag = getContent().indexOf("<buyPrices>");
		int idexBuyPriceEndTag = getContent().indexOf("</buyPrices>");
		String highBuyString = getContent().substring(idxBuyPriceStartTag,
				idexBuyPriceEndTag);
		String priceString = extractAttributValue("limit", highBuyString);
		result = new BigDecimal(priceString);
		return result;
	}

}
